package com.samehope.ar.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @Description: redis
 * @Author: ZhangLuo
 * @Email: 1946430@qq.com
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static RedisTemplate<String, String> template;

    @PostConstruct
    public void init() {
        template = redisTemplate;
    }

    private static ValueOperations<String, String> value() {
        return template.opsForValue();
    }

    /**
     * 永久性的存储
     * @param key
     * @param value
     */
    public static void set(String key, String value) {
        value().set(key, value);
    }

    /**
     * 设置过期时间的存储, 单位: 秒
     * @param key
     * @param value
     * @param seconds
     */
    public static void set(String key, String value, Long seconds) {
        value().set(key, value, seconds, TimeUnit.SECONDS);
    }

    /**
     * 判断是否存在的存储, 存储成功返回true, 存在则存储失败,返回false
     * @param key
     * @param value
     * @return
     */
    public static boolean setIfAbsent(String key, String value) {
        return value().setIfAbsent(key, value);
    }

    /**
     * 判断是否存在的存储, 存储成功返回true, 存在则存储失败,返回false
     * @param key
     * @param value
     * @return
     */
    public static boolean setIfAbsent(String key, String value, Long time, TimeUnit timeUnit) {
        return value().setIfAbsent(key, value, time, timeUnit);
    }

    /**
     * 获取值
     * @param key
     * @return
     */
    public static String get(String key) {
        return value().get(key);
    }
}
